//src/auth/auth.service.ts
import {
  Injectable,
  HttpException,
  HttpStatus
} from '@nestjs/common';
import { PrismaService } from 'prisma.service';
import { JwtService } from '@nestjs/jwt';
import { AuthEntity } from './entities/auth.entity';
import { decrypt as rsaDecrypt } from '../common/utils/rsa';
import { compare } from '../common/utils/crypt';
import { LoginDto } from './dto/login.dto';
import { JwtSign } from './jwt.sign';
import { RedisService } from 'src/redis/redis.service';

@Injectable()
export class AuthService {
  constructor(private prisma: PrismaService, private jwtService: JwtService, private redisService: RedisService) {}

  async login(body: LoginDto): Promise<AuthEntity> {
    const { phone, password } = body
    // Step 1: Fetch a user with the given phone
    const user = await this.prisma.user.findUnique({ where: { phone } });

    // If no user is found, throw an error
    if (!user) {
      throw new HttpException(`不存在手机号: ${phone}`, HttpStatus.OK);
    }

    // Step 2: Check if the password is correct
    const isPasswordValid = compare(rsaDecrypt(password), user.password)

    // If password does not match, throw an error
    if (!isPasswordValid) {
      throw new HttpException('手机号或密码错误', HttpStatus.OK);
    }
    const { password: userPassword, ...userInfo } = user
    userInfo.lastLoginTime = new Date()
    await this.prisma.user.update({
      where: {id: user.id},
      data: {
        lastLoginTime: userInfo.lastLoginTime
      }
    })
    const token = this.jwtService.sign({ userId: user.id } as JwtSign)
    await this.redisService.setValue(user.id, token)

    // Step 3: Generate a JWT containing the user's ID and return it
    return {
      userInfo,
      accessToken: token,
    };
  }
}
